package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{
    @Autowired
    private IStrategyCommentRepository dao;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IStrategyCommentService strategyCommentService;

    public boolean thumbUp(String toid, Long fromid) {
        Optional<StrategyComment> optional = dao.findById(toid);
        StrategyComment comment = optional.get();
        List<Long> thumbuplist = comment.getThumbuplist();

        boolean flag = false;
        //点赞
        if (!thumbuplist.contains(fromid)) {
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            thumbuplist.add(fromid);
            flag = true;
        }else {
            //取消点赞
            comment.setThumbupnum(comment.getThumbupnum() -1);
            thumbuplist.remove(fromid);
            flag = false;

        }
        this.save(comment);

        return flag;
    }

    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        //设置查询封装的对象
        Query query = new Query();

        //设置参数
        Criteria criteria =null;//条件分装对象
        if(qo.getDetailId() != -1){
            criteria = Criteria.where("detailId").is(qo.getDetailId());//等于
        }else {
            criteria = Criteria.where("detailId").ne(qo.getDetailId());//不等于
        }
        //添加查询条件
        query.addCriteria(criteria);
        //查询总条数
        long total = mongoTemplate.count(query, StrategyComment.class);
        if(total == 0 ){
            return Page.empty();
        }
        //分页对象
        //参数1.这里当前页从0开始,参数2 每页3显示条数
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        //排序对象
        //参数1.表示排序规则 desc 参数2 排序的字段
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(sort);

        //查询所有记录 数
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);
        return new PageImpl<StrategyComment>(list, pageable, total);
    }

    public void save(StrategyComment comment) {
        //如果这个id不等于null值
        if(comment.getId() == null ){
            //创建一个创建时间
            comment.setCreateTime(new Date());
        }

        dao.save(comment);
    }




}
